<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  type DataTableColumns,
  NSpace,
  NInput,
  NDatePicker,
  NSelect,
  NModal
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    width: '5rem'
  },
  {
    title: '年份',
    key: 'yearTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '姓名',
    key: 'userName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '部门',
    key: 'deptName',
    width: '10rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '创建人',
    key: 'addUserName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '总天数',
    key: 'addDay',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '使用天数',
    key: 'subDay',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '最后有效时间',
    key: 'endTime',
    width: '10rem',
    align: useStore.isCenter,
    render(e: any) {
      return e.endTime ? e.endTime.slice(0, 10) : ''
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          color: useStore.color['delete'],
          disabled: e.subDay ? true : false,
          onClick: () => handleDelete([e?.id])
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]

//日期选择器
const timeRange: any = ref(null)
function handleUpdateFormattedValue(e: string[]) {
  if (timeRange.value == null) {
    formData.yearTime = null
  } else {
    formData.yearTime = e
  }
}

//筛选条件
type formType = {
  yearTime: any
  userName: any
  deptId: any
}
const formData = reactive<formType>({
  yearTime: null, //指标
  userName: null,
  deptId: null
})

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

//部门类型
const partList: any = ref([])
const getPartName = async () => {
  const [error, res] = await sendRequest({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return message.error(error.message)
  partList.value = res.data
}
getPartName()

//新增
const handleAdd = () => {
  router.push({
    path: '/OA/Office/AddHoliday'
  })
}

//删除弹窗
const modalVisible = ref(false)
const modalId = ref()
const againDelete = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'holidayDelete',
    override: {
      data: modalId.value
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.data)
  modalVisible.value = false
  queryTableData(true)
}

//删除
const handleDelete = (val: any) => {
  modalId.value = val
  modalVisible.value = true
}

const handleBatchDelete = () => {
  const tmp = chosenList.value.some((i: any) => i.subDay > 0)
  if (tmp) {
    message.warning('已使用的假期不可删除！')
  } else {
    modalVisible.value = true
    modalId.value = dataListSelections.value
  }
}

//多选框勾选
type DataListSelectionsItem = {
  id: string
}
const dataListSelections: any = ref<DataListSelectionsItem[]>([])
const chosenList = ref<any>([])
function selectionChangeHandle(val: any, info: any) {
  dataListSelections.value = val
  chosenList.value = info
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  dataListSelections.value = []
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'holidayList',
    override: {
      params: {
        ...formData,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
}

//导入excel
const handleImport = () => {
  router.push({
    path: '/OA/Office/ImportHoliday'
  })
}

//导出excel
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const exportLoading = ref(false)
async function handleExport() {
  exportLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'office',
    api: 'holidayExport',
    override: {
      params: {
        ...formData,
        page: 1,
        limit: 99999
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '假期列表数据')
  exportLoading.value = false
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Office/holidaySetting') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NFormItem label="年份:">
            <NDatePicker input-readonly placeholder="请选择年份" type="year" v-model:value="timeRange"
              @update-formatted-value="handleUpdateFormattedValue" clearable />
          </NFormItem>
          <NFormItem label="姓名:">
            <NInput placeholder="输入姓名" v-model:value="formData.userName" clearable />
          </NFormItem>
          <NFormItem label="部门:">
            <NSelect :options="partList" v-model:value="formData.deptId" placeholder="请选择部门" clearable
              style="width: 200px" filterable label-field="name" value-field="value" />
          </NFormItem>
          <NFormItem>
            <NButton type="primary" ghost @click="queryTableData(true)">
              查询
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton type="error" style="width: 115px" @click="handleBatchDelete"
            :disabled="dataListSelections.length ? false : true" ghost>
            删除选中
          </NButton>
          <NButton type="primary" style="width: 115px" @click="handleImport" ghost>
            导入Excel
          </NButton>
          <NButton type="primary" style="width: 115px" :loading="exportLoading" @click="handleExport" ghost>
            导出Excel
          </NButton>
          <NButton type="primary" style="width: 115px" @click="handleAdd">
            新增假期
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" :checked-row-keys="dataListSelections" @update:checked-row-keys="selectionChangeHandle" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againDelete" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
